package com.mail.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import com.mail.common.DataResult;
import com.mail.dto.EmailConfigIdDto;
import com.mail.dto.SendEmailDto;
import com.mail.enums.ResponseCode;
import com.mail.service.EmailConfigService;
import com.mail.utils.MailSendUtil;
import com.yang.yangutils.utils.YangUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import  com.mail.constant.AuthServerConstant;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/email")
public class SendEmailController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String mailUsername;

    @Resource
    private EmailConfigService emailConfigService;

    /**
     * 发送邮件
     */
    @GetMapping("/sendEmail")
    public DataResult sendEmail(String toMail) {
        if (!StringUtils.isEmpty(toMail) & toMail != null) {
            String redisCode = (String) redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + toMail);
            if (!StringUtils.isEmpty(redisCode)) {
                long time = Long.parseLong(redisCode.split("_")[1]);
                if (System.currentTimeMillis() - time < 60000) {
                    //60秒内不能再发
                    return DataResult.error(ResponseCode.SMS_CODE_EXCEPTION.getCode(), ResponseCode.SMS_CODE_EXCEPTION.getMsg());
                }
            }
        }
        String code = getCode(toMail);
        //2.验证码有效时间
        //String code1 = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        String code2 = code + "_" + System.currentTimeMillis();
        //redis缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + toMail, code2, 10, TimeUnit.MINUTES);

        SimpleMailMessage massage = new SimpleMailMessage();
        massage.setFrom(mailUsername);
        massage.setTo(toMail);
        massage.setSubject("黑客帝国为你服务，请收好你的验证码：");
        massage.setText(code);//发送内容为验证码
        mailSender.send(massage);
        return DataResult.success("发送成功!");
    }

    /**
     * 校验邮件
     */
    @PostMapping("/checkEmail")
    public DataResult checkEmail(String code,String mail) {
        //从redis获取缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(mail);
        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果能够比对成功，说明登录成功

            //如果用户登录成功，删除redis中缓存的验证码
            redisTemplate.delete(mail);

            log.info("==================验证码校验成功！====================");
            return DataResult.success("验证码校验成功！");
        }else{
            return DataResult.success("验证码校验失败！");
        }
    }

    //随机生成6位数字
    public String getCode(String mail) {
        String code = YangUtils.getCode();

        log.info("==============验证码=" + code);

        redisTemplate.opsForValue().set(mail, code, 60, TimeUnit.SECONDS);
        return code;
    }

    /**
     * 超级发送邮件
     */
    @PostMapping("/superMails")
    public DataResult superEmails(SendEmailDto sendEmailDto){
        String msg="";
        if(sendEmailDto.getFiles()==null){
            msg= MailSendUtil.sendTextMail(sendEmailDto);
        }else{
            msg= MailSendUtil.sendFileMail(sendEmailDto);
        }
        if(msg==null) {
            return DataResult.success("发送成功！");
        }else{
            return DataResult.error(msg);
        }
    }

    /**
     * 加配置发送邮件
     */
    @PostMapping("/configMails")
    public DataResult configEmails(EmailConfigIdDto emailConfigIdDto){
        return emailConfigService.queryEmailByAccount(emailConfigIdDto);
    }
}
